<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :multiple="multiple"
      :limit="limit"
      :on-exceed="hanleExceed"
      :on-preview="preview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="upload"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :class="{ disabled: fileList.length >= limit }"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-dialog title="预览" :visible="showDialog" @close="close">
      <el-row type="flex" justify="center">
        <img :src="imgurl" alt="" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    //是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    //允许上传数量
    limit: {
      type: Number,
      default: 1,
    },
    //支持上传的格式
    imgType: {
      type: Array,
      default() {
        return ["image/jpeg", "image/jpg", "image/png"];
      },
    },
    //图片数组
    pictureList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      imgurl: "", //预览图片url
      showDialog: false, //预览图片弹窗
      fileList: [], //图片数组
      imgTypeStr: "", //支持上传格式文字
    };
  },
  methods: {
    // 浏览
    preview(data) {
      this.showDialog = true;
      this.imgurl = data.url;
    },
    close() {
      this.showDialog = false;
    },
    // 删除
    onRemove(file, fileList) {
      this.fileList = [...fileList];
      this.$emit("receiveData", this.fileList);
    },
    // 修改
    onChange(file, fileList) {
      this.fileList = [...fileList];
      this.$emit("receiveData", this.fileList);
    },
    // 上传之前
    beforeUpload(file) {
      //拼接白名单文本
      this.imgType.forEach((item, index) => {
        if (index == this.imgType.length - 1)
          this.imgTypeStr += `${item.split("/")[1]}`;
        else this.imgTypeStr += `${item.split("/")[1]},`;
      });

      // 判断图片格式
      if (!this.imgType.includes(file.type)) {
        this.$message.error(`图片目前只支持${this.imgTypeStr}格式`);
        return false;
      }

      // 设置图片最大内存
      const max = 1024 * 1024 * 2;
      
      // 判断图片大小
      if (file.size > max) {
        this.$message.error("图片不能大于2M");
        return false;
      }
    },
    // 自定义上传
    upload() {},
    //超出指定上传数量
    hanleExceed() {
      this.$message.warning(`最多可上传${this.limit}张图片`);
    },
    //清空数组
    handleEmptyFileList() {
      this.fileList = [];
    },
  },
};
</script>

<style lang="less" scoped>
.disabled {
  /deep/ .el-upload--picture-card {
    display: none;
  }
}
</style>
